package com.iplay.component.excel;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import com.iplay.component.excel.exception.ExcelIOException;

public class ExcelUtils {
	private ExcelUtils() {
	}

	public static List<String[]> readExcel(InputStream excel, String sheetName) throws ExcelIOException {
		List<String[]> data = new ArrayList<>();
		try {
			Workbook workbook = WorkbookFactory.create(excel);
			Sheet sheet = workbook.getSheet(sheetName);
			if(sheet == null)
				throw new ExcelIOException("Sheet with name: "+sheetName+" doesn't  exist!");
			int numOfRows = sheet.getPhysicalNumberOfRows();
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd");
			for (int i = 0; i < numOfRows; i++) {
				Row row = sheet.getRow(i);
				int numOfCells = row.getPhysicalNumberOfCells();
				String[] cells = new String[numOfCells];
				for (int j = 0; j < numOfCells; j++) {
					Cell cell = row.getCell(j);
					String cellValue = null;
					switch (cell.getCellTypeEnum()) {
					case STRING:
						cellValue = cell.getStringCellValue();
						break;
					case NUMERIC:
						if (DateUtil.isCellDateFormatted(cell)) {
							cellValue = dateFormat.format(cell.getDateCellValue());
						} else {
							cellValue = String.valueOf(cell.getNumericCellValue());
						}
						break;
					case BOOLEAN:
						cellValue = String.valueOf(cell.getBooleanCellValue());
						break;
					case BLANK: 
						cellValue = cell.getStringCellValue();
						break;
					case FORMULA:
						cellValue = "";
						break;
					default:
						cellValue = "";
					}
					cells[j] = cellValue;
				}
				data.add(cells);
			}
		} catch (EncryptedDocumentException | InvalidFormatException | IOException e) {
			throw new ExcelIOException(e.getMessage(), e);
		}
		return data;
	}
}
